<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\tools\Tool;
use app\tools\WxPay;
use app\models\Customer;
use app\models\CustomerAddress;
use app\models\OrderInfo;
use app\models\Merchant;

class OrderController extends BaseController
{

  public $state_name_arr = ['待支付','支付成功','待退款','退款成功','退款失败','服务中','已完成'];

  public function actionAddOrder(){
    $openid = Yii::$app->request->post('openid', '');
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $good_id = Yii::$app->request->post('good_id', 0);
    $unit_price = Yii::$app->request->post('unit_price', 0);
    $num = Yii::$app->request->post('num', 0);
    $address_id = Yii::$app->request->post('address_id', 0);
    $remark = Yii::$app->request->post('remark', '');
    if (empty($openid) || empty($shop_id) || empty($good_id) || empty($unit_price) || empty($num) || empty($address_id)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    $customer_info = Customer::find()->where(['openid' => $openid])->one();
    if (!$customer_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
    $customer_address = CustomerAddress::findOne($address_id);
    if (!$customer_address) {
      return Re::data(null, '用户地址信息读取错误', Re::ERROR);
    }
    $order_info = new OrderInfo();
    
    $order_info->shop_id = $shop_id;
    $order_info->customer_id = $customer_info->id;
    $order_info->good_id = $good_id;
    $order_info->order_sn = Tool::getSn('B');
    $order_info->unit_price = $unit_price;
    $order_info->num = $num;
    $order_info->money = $unit_price * $num;
    $order_info->order_type = 1;
    $order_info->remark = $remark;
    $order_info->address_name = $customer_address->name;
    $order_info->address_phone = $customer_address->phone;
    $order_info->address = $customer_address->area->parentArea->parentArea->name.$customer_address->area->parentArea->name.$customer_address->area->name.$customer_address->address;
    if (!$order_info->save()) {
      return Re::data(null, $order_info->showErrors(), Re::ERROR);
    }
    return Re::data(['data' => $order_info->order_sn]);
  }

  public function actionOrderCount(){
    $openid = Yii::$app->request->post('openid', '');
    $customer_info = Customer::find()->where(['openid' => $openid])->one();
    if (!$customer_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
    $over_time = time() - 7200;
    $order_count_dzf = (int)OrderInfo::find()
      ->where(['order_type' => 1, 'customer_id' => $customer_info->id, 'state' => 0])
      ->andWhere(['>', 'created_at', $over_time])
      ->count();//待支付订单数量
    $order_count_yzf = (int)OrderInfo::find()->where(['order_type' => 1, 'customer_id' => $customer_info->id, 'state' => 1])->count();//已支付订单数量
    $order_count_fwz = (int)OrderInfo::find()->where(['order_type' => 1, 'customer_id' => $customer_info->id, 'state' => 5])->count();//服务中订单数量
    $order_count_ywc = (int)OrderInfo::find()->where(['order_type' => 1, 'customer_id' => $customer_info->id, 'state' => 6])->count();//已完成订单数量
    $order_count_sh = (int)OrderInfo::find()->where(['order_type' => 1, 'customer_id' => $customer_info->id, 'state' => 2])->count();//售后订单数量
    $data = [
      'order_count_dzf' => $order_count_dzf,
      'order_count_yzf' => $order_count_yzf,
      'order_count_fwz' => $order_count_fwz,
      'order_count_ywc' => $order_count_ywc,
      'order_count_sh' => $order_count_sh
    ];
    return Re::data(['data' => $data]);
  }
  
  public function actionOrderList(){
    $openid = Yii::$app->request->post('openid', '');
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 20);
    $state = Yii::$app->request->post('state', -1);
    $customer_info = Customer::find()->where(['openid' => $openid])->one();
    if (!$customer_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
    $over_time = time() - 7200;
    $query = OrderInfo::find()->where(['order_type' => 1, 'customer_id' => $customer_info->id]);
    if ($state != -1) {
      if (!is_numeric($state)) {
        $state = explode(',', $state);
      }
      if (!$state) {
        $query->andWhere(['state' => $state])->andWhere(['>', 'created_at', $over_time]);
      } else {
        $query->andWhere(['state' => $state]);
      }
    }
    $list = $query->orderBy('created_at desc')->limit($page_size)->offset($page_size*$page)->all();
    $data = [];
    if ($list) {
      foreach($list as $v) {
        $order_state = $v->state;
        if ($v->state == 0 && $v->created_at+7200<time()) {
          $order_state = -1;
        }
        $data[] = [
          'id' => $v->id,
          'order_sn' => $v->order_sn,
          'shop_name' => $v->shop->name,
          'cate_name' => $v->good->goodCate->parent->name.'/'.$v->good->goodCate->name,
          'good_name' => $v->good->name,
          'good_cover' => $v->good->cover,
          'unit_price' => $v->unit_price,
          'num' => $v->num,
          'money' => $v->money,
          'state' => $order_state,
          'state_name' => $order_state == -1 ? '已取消' : $this->state_name_arr[$v->state],
          'created_time' => date('Y-m-d H:i:s', $v->created_at)
        ];
      }
    }
    return Re::data(['data' => $data]);
  }

  public function actionOrderInfo(){
    $order_sn = Yii::$app->request->post('order_sn', '');
    $order_info = OrderInfo::find()->where(['order_type' => 1, 'order_sn' => $order_sn])->one();
    if (!$order_info) {
      return Re::data(null, '订单信息读取错误', Re::ERROR);
    }

    $order_refund_data = [];
    $order_refund = OrderInfo::find()->where(['relate_id' => $order_info->id, 'order_type' => 2])->one();
    if ($order_refund) {
      $order_refund_data = [
        'refund_sn' => $order_refund->order_sn,
        'refund_remark' => $order_refund->refund_remark,
        'refund_time' => date("Y-m-d H:i:s", $order_refund->created_at),
        'refund_audit_state_name' => $order_refund->refund_audit_state ? ($order_refund->refund_audit_state == 1 ? '已同意' : '已拒绝') : '未审核',
        'refund_audit_remark' => $order_refund->refund_audit_remark,
        'refund_audit_admin_name' => $order_refund->refund_audit_admin ? $order_refund->admin->name : '',
        'refund_audit_time' => $order_refund->refund_audit_at ? date("Y-m-d H:i:s", $order_refund->refund_audit_at) : '',
      ];
    }

    $data = [
      'id' => $order_info->id,
      'order_sn' => $order_info->order_sn,
      'shop_name' => $order_info->shop->name,
      'shop_phone' => $order_info->shop->phone,
      'cate_name' => $order_info->good->goodCate->parent->name.'/'.$order_info->good->goodCate->name,
      'good_name' => $order_info->good->name,
      'good_cover' => $order_info->good->cover,
      'unit_price' => $order_info->unit_price,
      'num' => $order_info->num,
      'money' => $order_info->money,
      'state' => $order_info->state,
      'state_name' => $this->state_name_arr[$order_info->state],
      'address_name' => $order_info->address_name,
      'address_phone' => $order_info->address_phone,
      'address' => $order_info->address,
      'created_time' => date('Y-m-d H:i:s', $order_info->created_at),
      'pay_time' => $order_info->pay_at ? date('Y-m-d H:i:s', $order_info->pay_at) : '',
      'service_start_at_time' => $order_info->service_start_at ? date('Y-m-d H:i:s', $order_info->service_start_at) : '',
      'service_start_img' => $order_info->service_start_img,
      'service_finsh_time' => $order_info->service_finsh_at ? date('Y-m-d H:i:s', $order_info->service_finsh_at) : '',
      'service_finsh_img' => $order_info->service_finsh_img,
      'order_refund_data' => $order_refund_data
    ];
    return Re::data(['data' => $data]);
  }

  public function actionOrderRefund(){
    $order_sn = Yii::$app->request->post('order_sn', '');
    $refund_remark = Yii::$app->request->post('refund_remark', '');
    $order_info = OrderInfo::find()->where(['order_type' => 1, 'order_sn' => $order_sn])->one();
    if (!$order_info) {
      return Re::data(null, '订单信息读取错误', Re::ERROR);
    }
    $order_refund = new OrderInfo();
    $order_refund->relate_id = $order_info->id;
    $order_refund->shop_id = $order_info->shop_id;
    $order_refund->customer_id = $order_info->customer_id;
    $order_refund->good_id = $order_info->good_id;
    $order_refund->order_sn = Tool::getSn('R');
    $order_refund->unit_price = $order_info->unit_price;
    $order_refund->num = $order_info->num;
    $order_refund->money = $order_info->money;
    $order_refund->order_type = 2;
    $order_refund->refund_remark = $refund_remark;
    if (!$order_refund->save()) {
      return Re::data(null, '退款记录保存失败', Re::ERROR);
    }
    $order_info->state = 2;
    if (!$order_info->save()) {
      return Re::data(null, '订单状态更新失败', Re::ERROR);
    }
    return Re::data();
  }

  public function actionOrderPay() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$openid = Yii::$app->request->post('openid', '');
		$order = OrderInfo::find()->where(['order_type' => 1, 'order_sn' => $order_sn])->one();
		if (empty($order)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
    }
		$body_name = "购买" . $order->good->name;
		$merchant = Merchant::find()->where(['status' => 1])->one();
		$mch_id = $merchant->mch_id;
		$mch_key = $merchant->mch_key;
    $order->mch_id = $mch_id;
		$order->mch_key = $mch_key;
    $order->save();
    $trade_type = "JSAPI";
    $notify_url = Yii::$app->params['domain'] . '/order/notify-order';
    $res = WxPay::pay($mch_id, $order, $openid, $mch_key, $body_name, $trade_type, $notify_url);

		//生成新的签名给前端支付
		$pay_param['appId'] = $res->appid;
		$pay_param['timeStamp'] = time();
		$pay_param['nonceStr'] = $res->nonce_str;
		$pay_param['package'] = 'prepay_id=' . $res->prepay_id;
    $pay_param['signType'] = 'MD5';
    $pay_sign = WxPay::getSign($pay_param, $mch_key);
		return Re::data(['data' => $res, 'time_tamp' => time().'', 'pay_sign' => $pay_sign]);
	}

  //微信支付回调
	public function actionNotifyOrder() {
		$testxml  = file_get_contents("php://input");
		$jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
		$result = json_decode($jsonxml, true);//转成数组，
		if($result){
			//如果成功返回了
			$out_trade_no = $result['out_trade_no'];
			if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
				$order = OrderInfo::find()->where(['order_type' => 1, 'order_sn' => $out_trade_no])->one();
				if ($order && !$order->state) {//待支付
					$order->pay_at = time();
					$order->state = 1;
					if (!$order->save()) {
						return Re::data(null, '订单操作失败', Re::ERROR);
					}
				}
			}
		}
		$xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		echo $xml;
	}
}
